// script.js
const ball = document.getElementById('ball');
const paddle = document.getElementById('paddle');
const gameContainer = document.getElementById('game-container');
const scoreValue = document.getElementById('score-value');

let ballX = 0;
let ballY = 0;
let ballSpeedX = 5;
let ballSpeedY = 5;
let paddleSpeed = 15;
let score = 0;

function updateGame() {
  // 移动球
  ballX += ballSpeedX;
  ballY += ballSpeedY;

  // 反弹球
  if (ballX + ball.clientWidth > gameContainer.clientWidth || ballX < 0) {
    ballSpeedX = -ballSpeedX;
  }
  if (ballY + ball.clientHeight > gameContainer.clientHeight || ballY < 0) {
    ballSpeedY = -ballSpeedY;
  }

  // 检测球与挡板碰撞
  if (
    ballY + ball.clientHeight >= paddle.offsetTop &&
    ballX >= paddle.offsetLeft &&
    ballX <= paddle.offsetLeft + paddle.clientWidth
  ) {
    ballSpeedY = -ballSpeedY;
    score++;
    updateScore();
    animatePaddle(); // 调用挡板动画效果
  }

  // 更新球的位置
  ball.style.left = ballX + 'px';
  ball.style.top = ballY + 'px';

  requestAnimationFrame(updateGame);
}

function movePaddle(event) {
  // 移动挡板
  if (event.key === 'ArrowLeft' && paddle.offsetLeft > 0) {
    paddle.style.left = paddle.offsetLeft - paddleSpeed + 'px';
  } else if (event.key === 'ArrowRight' && paddle.offsetLeft + paddle.clientWidth < gameContainer.clientWidth) {
    paddle.style.left = paddle.offsetLeft + paddleSpeed + 'px';
  }
}

function updateScore() {
  scoreValue.textContent = score;
}

function animatePaddle() {
  // 在碰撞时给挡板添加动画效果
  paddle.style.transform = 'scale(1.2)';
  setTimeout(() => {
    paddle.style.transform = 'scale(1)';
  }, 100); // 0.1秒后还原
}

document.addEventListener('keydown', movePaddle);
updateGame();
